<?php

require_once $_SERVER['DOCUMENT_ROOT'] . '/../library/Apache/Solr/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/../library/Apache/Solr/Document.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/../library/Apache/Solr/HttpTransport/Curl.php';
Yii::import('ext.search.interfaces.ISearchInterface');

class SolrSearchAdapter implements ISearchInterface
{

    private $_service;

    public function __construct()
    {
	$this->getService();
    }

    public function getService()
    {
	if ($this->_service === null) {
	    $this->_service = new Apache_Solr_Service(
			    Yii::app()->params['solr']['host'],
			    Yii::app()->params['solr']['port'],
			    Yii::app()->params['solr']['path'],
			    new Apache_Solr_HttpTransport_Curl()
	    );
	}
	return $this->_service;
    }

    public function deleteById($id)
    {
	if (!$id || !$this->getService()->ping()) {
	    return false;
	}
	$this->getService()->deleteById($id);
	$this->getService()->commit();
    }

    public function search($query, $offset = 0, $limit = 10, $params = array())
    {
	if (!$query || !$this->getService()->ping()) {
	    return false;
	}
	return $this->getService()->search($query, $offset, $limit, $params);
    }

    public function toIndex(array $data)
    {
	if (!is_array($data)) {
	    return false;
	}
	$data = array_filter($data);
	if (empty($data)) {
	    return false;
	}
	if (!$this->getService()->ping()) {
	    return false;
	}
	$doc = new Apache_Solr_Document();
	foreach ($data as $key => $value) {
	    $doc->$key = $value;
	}
	$this->getService()->addDocument($doc);
	$this->getService()->commit();
    }

}
